package com.example.music_player

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.music_player.data.AppDatabase
import com.example.music_player.data.User
import kotlinx.coroutines.launch

class AdminActivity : AppCompatActivity() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var userAdapter: UserAdapter
    private lateinit var logoutButton: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_admin)

        // 初始化 RecyclerView
        recyclerView = findViewById(R.id.recycler_view_users)
        recyclerView.layoutManager = LinearLayoutManager(this)

        // 加载用户列表
        loadUsers()

        // 初始化退出按钮
        logoutButton = findViewById(R.id.btn_logout)
        logoutButton.setOnClickListener {
            val intent = Intent(this@AdminActivity, MainActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) // 清除所有上面的活动
            startActivity(intent)
            finish() // 结束当前活动
        }

    }

    private fun loadUsers() {
        lifecycleScope.launch {
            val userDao = AppDatabase.getDatabase(this@AdminActivity).userDao()
            val users = userDao.getAllUsers() // 获取所有用户
            userAdapter = UserAdapter(this@AdminActivity, users) // 初始化适配器
            recyclerView.adapter = userAdapter // 设置适配器
        }
    }
}
